import axios from "axios"
import { ThunkAction } from "redux-thunk"
import { BASE_URL } from "../../config"
import { RootState } from "../store"

// 正在调用推荐信息api
export const FETCH_RECOMMEND_PRODUCTS_START = "fetch_recommend_products_start"
// 推荐信息api调用成功
export const FETCH_RECOMMEND_PRODUCTS_SUCCESS =
  "fetch_recommend_products_success"
// 推荐信息api调用失败
export const FETCH_RECOMMEND_PRODUCTS_FAIL = "fetch_recommend_products_fail"

interface FetchRecommendProductsStartAction {
  type: typeof FETCH_RECOMMEND_PRODUCTS_START
}

interface FetchRecommendProductsSuccessAction {
  type: typeof FETCH_RECOMMEND_PRODUCTS_SUCCESS
  payload: any
}

interface FetchRecommendProductsFailAction {
  type: typeof FETCH_RECOMMEND_PRODUCTS_FAIL
  payload: any
}

export type RecommendProductAction =
  | FetchRecommendProductsStartAction
  | FetchRecommendProductsSuccessAction
  | FetchRecommendProductsFailAction

// 开始获取数据的action
export const fetchRecommendProductsStartActionCreator =
  (): FetchRecommendProductsStartAction => {
    return {
      type: FETCH_RECOMMEND_PRODUCTS_START,
    }
  }

// 获取数据成功的action
export const fetchRecommendProductsSuccessActionCreator = (
  data
): FetchRecommendProductsSuccessAction => {
  return {
    type: FETCH_RECOMMEND_PRODUCTS_SUCCESS,
    payload: data,
  }
}

// 获取数据失败的action
export const fetchRecommendProductsFailActionCreator = (
  error
): FetchRecommendProductsFailAction => {
  return {
    type: FETCH_RECOMMEND_PRODUCTS_FAIL,
    payload: error,
  }
}

// thunk可以返回一个函数，而不一定是js对象
// 在一个thunk中，action可以完成一系列连续的action操作
// 并且可以处理异步逻辑
// 业务逻辑可以从ui层面挪到这里，代码分层会更清晰
export const giveMeDataActionCreator =
  (): ThunkAction<void, RootState, unknown, RecommendProductAction> =>
  async (dispatch, getState) => {
    dispatch(fetchRecommendProductsStartActionCreator())
    try {
      const res = await axios.get(`${BASE_URL}/productList`)
      const { data } = res.data
      dispatch(fetchRecommendProductsSuccessActionCreator(data))
    } catch (error) {
      dispatch(fetchRecommendProductsFailActionCreator(error.message))
    }
  }
